//index.js
//获取应用实例
const app = getApp()
Page({

  data: {
    cw: 300,
    ch: 200,
    uploadPic: '../../img/me.jpg',
    limit:60,
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onLoad:function(){ 
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getUserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  onGotUserInfo: function (e) {
    console.log(e.detail.errMsg)
    console.log(e.detail.userInfo)
    console.log(e.detail.rawData)
    var res=e.detail;
    let userinfo;
    if (res.rawData) {
      userinfo = res.rawData;
    } else {
      userinfo = res.userinfo;
    }
     
    getApp().globalData.userInfo = userinfo
    wx.setStorageSync('userinfo', userinfo)

    userinfo = JSON.parse(userinfo);
    userinfo.openid = wx.getStorageSync('user_openid');
    wx.request({
      url: wx.getStorageSync('host') + '/weiuser/add',
      data: userinfo,
      success: function (ret) {
        wx.setStorageSync('weiuser', ret.data.data);
      }
    })

    wx.switchTab({
      url: '/pages/index/index',
    })
  },

  sendmsg:function(){
    wx.requestSubscribeMessage({
      tmplIds: ['aMmE-Fsg2jsMPprQfVjYz9D-SMfGfll2qUWfALiuwSs','p2W5OWj0aZYWkwb1GtuyNa777Q0kLhFk06ziDJsE0yI'],
      success(res) { 
        console.log("success:"+res);
      },
      fail(res){
        console.log("fail:" + res.errMsg + ":" + res.errCode);
      }
    })
  },

  uploadImg(e) {
    let that = this;
    console.log(e);
    let index = e.currentTarget.dataset.number;
    let uploadFile = ''; // 最后处理完，图片上传的图片地址
    wx.chooseImage({
      success(res) {
        console.log(res)
        //const tempFilePaths = res.tempFilePaths;

        var file = res.tempFiles[0];
        const tempFilePaths = file.path;
        var filesize = file.size;
        console.log("filesize:" + filesize);
        if (filesize > that.data.limit * 1024) {

        } else {
          //直接上传
          console.log("直接上传");
          that.uploadImageToServer(tempFilePaths);
        }

        // 获得原始图片大小
        wx.getImageInfo({
          src: tempFilePaths,
          success(res) {
            // console.log ('获得原始图片大小',res.width)
            //console.log (res.height)
            var originWidth, originHeight;
            originHeight = res.height;
            originWidth = res.width;
            console.log(originWidth);
            // 压缩比例
            // 最大尺寸限制
            var maxWidth = 200,
              maxHeight = 200;
            // 目标尺寸
            var targetWidth = originWidth,
              targetHeight = originHeight;
            // 等比例压缩，如果宽度大于高度，则宽度优先，否则高度优先
            if (originWidth > maxWidth || originHeight > maxHeight) {
              if (originWidth / originHeight > maxWidth / maxHeight) {
                // 要求宽度*(原生图片比例)=新图片尺寸
                targetWidth = maxWidth;
                targetHeight = Math.round(maxWidth * (originHeight / originWidth));
              } else {
                targetHeight = maxHeight;
                targetWidth = Math.round(maxHeight * (originWidth / originHeight));
              }
            }

            // 更新 canvas 大小
            that.setData({
              cw: targetWidth,
              ch: targetHeight
            });
            // 尝试压缩文件，创建 canvas
            var ctx = wx.createCanvasContext('firstCanvas');
            ctx.clearRect(0, 0, targetWidth, targetHeight);
            ctx.drawImage(tempFilePaths[0], 0, 0, targetWidth, targetHeight);
            ctx.draw(false, function () {
              // 获得新图片输出
              wx.canvasToTempFilePath({
                canvasId: 'firstCanvas',
                success: (res) => {
                  // 写入图片数组
                  
                  uploadFile = res.tempFilePath;
                  that.uploadImageToServer(uploadFile);
                  
                },
                fail: (err) => {
                  console.error(err)
                }
              }, this)
            });

          }
        })

      }
    })
  },
  uploadImageToServer:function(file){
    var that=this;
    wx.uploadFile({
      url: wx.getStorageSync('host') + '/file/uploadImage', // 仅为示例，非真实的接口地址
      filePath: file,
      name: 'image',
      formData: {
        'user': 'test' 
      },
      success(res) {
        var data=JSON.parse(res.data);
        //const data = res.data
        that.setData({ uploadPic: wx.getStorageSync('imghost') + data.data})
      }
    })
  },


  
})